﻿using System;
using System.Web.UI;
using System.Data.SqlClient;

public partial class Sqls_EditDBTable : Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {

        }
    }

    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        try
        {
            string tablename = "U_" + StringHelper.ReplaceBadChar(txtTableName.Text);
            
            string sql = "create table ["+tablename +"](";
            if (chklColumn.Items[0].Selected)
            {
                sql += "[id] [int] IDENTITY(1,1) NOT NULL  CONSTRAINT [PK_"+tablename+"] PRIMARY KEY CLUSTERED (	[id] ASC )WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON),";
            }
            if (chklColumn.Items[1].Selected)
            {
                sql += "userid int NULL,";
            }
            if (chklColumn.Items[2].Selected)
            {
                sql += "adminid int NULL,";
            }
            if (chklColumn.Items[3].Selected)
            {
                sql += "[addtime] [datetime] NULL CONSTRAINT [DF_"+tablename+"_addtime]  DEFAULT (getdate()),";
            }
            if (chklColumn.Items[4].Selected)
            {
                sql += "[updatetime] [datetime] NULL CONSTRAINT [DF_" + tablename + "_updatetime]  DEFAULT (getdate()),";
            }
            if (sql.EndsWith(","))
            {
                sql = sql.Remove(sql.Length - 1, 1);
            }
            sql += ") ON [PRIMARY]";
            sql += " EXECUTE sp_addextendedproperty N'MS_Description',@description, N'user', N'dbo', N'table', N'" + tablename + "', NULL, NULL";
            SqlParameter[] paras =
            {
                new SqlParameter("@description",txtBrief.Text.Trim())
            };
           DbHelperSQL.ExecuteSql(sql,paras);
           lblResult.Text = "操作成功!";
           ClientScript.RegisterClientScriptBlock(this.GetType(), "", "Finish()", true);
        }
        catch
        {
            lblResult.Text = "创建失败,可能表已经存在!";
        }

    }
    protected override void OnInit(EventArgs e)
    {
        if (!IsPostBack)
        {
            //添加访问权限的逻辑,session和server.avariable["refer"]以及主机名称.防止跨域提交表单
            if (Request.ServerVariables["HTTP_Referer"] == null || Request.ServerVariables["REMOTE_HOST"] == null || Request.ServerVariables["SERVER_NAME"] != Request.Url.Host)
            {
                Response.Write("非法访问!");
                Response.End();
                return;
            }
        }
    }
}
